<template>
  <div class="search-container">
      <!-- 搜索输入框 -->
      <van-search
        class="search-input"
        v-model="searchText"
        @search="onSearchhandle"
        @focus="isShowResult = false"
        shape="square"
        show-action
        background="#3296fa"
        placeholder="请输入要搜索的内容..."
      >
      <van-button slot="action" @click="$router.back()" text="取消" class="remove-btn"></van-button>
      </van-search>
      <!-- 搜索搜索结果 -->
      <search-result v-if="isShowResult" :q="searchText"></search-result>
      <!-- 搜索联想建议 当搜索框输入内容时 请求加载联想数据-->
      <search-suggestion v-else-if="searchText" :q="searchText" @onSearchSuggestion="onSearchhandle"></search-suggestion>
      <!-- 搜索历史记录 -->
      <search-history
      v-else
      :searchHistoryData="searchHistoryData"
      @deleteHistory="deleteHistoryhandle"
      @searchHistory="onSearchhandle"
      @clear-all-search-history="searchHistoryData=[]"
      ></search-history>
  </div>
</template>

<script>
// 导入对应组件
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
// 导入存储本地仓库方法
import { getLocalStorageItem, setLocalStorageItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    'search-history': SearchHistory,
    'search-suggestion': SearchSuggestion,
    'search-result': SearchResult
  },
  data () {
    return {
      // 文本框用户输入内容
      searchText: '',
      // 组件显示与隐藏
      isShowResult: false,
      // 历史数据如果本地没有则为空数组
      searchHistoryData: getLocalStorageItem('SEARCH_HISTORY') || []
    }
  },
  methods: {
    // 搜索确认触发事件 val值为历史记录子组件要求搜索关键字为item的文章
    onSearchhandle (val) {
      // 更新文本框内容
      this.searchText = val
      // 存储搜索历史
      // 要求：不要有重复历史数据，最新的排前面
      const index = this.searchHistoryData.indexOf(val)
      if (index !== -1) {
        this.searchHistoryData.splice(index, 1)
      }
      this.searchHistoryData.unshift(val)
      this.isShowResult = true
    },
    // 子组件要求删除索引为index的历史记录
    deleteHistoryhandle (index) {
      this.searchHistoryData.splice(index, 1)
    }
  },
  watch: {
    searchHistoryData (value) {
      setLocalStorageItem('SEARCH_HISTORY', value)
    }
  }
}
</script>

<style scoped lang="less">
.search-input {
    padding: 40px 0 17px 34px;
    height: 128px;
  .van-search__content {
      padding: 0 0 5px 5px;
      width: 589px;
      height: 56px;
      .van-cell {
        padding: 4px;
      }
  }
  .van-search__action {
    line-height: unset;
    padding: 0;
    .remove-btn {
    border: unset;
    height: 56px;
    color: #fff;
    background-color: #3296fa;
    font-size: 28px;
    }
  }

}
</style>
